package com.liqi.device.service.impl;

import com.liqi.common.annotation.DataScope;
import com.liqi.common.constant.RedisConstants;
import com.liqi.common.constant.UserConstants;
import com.liqi.common.core.redis.RedisCache;
import com.liqi.common.utils.DateUtils;
import com.liqi.common.utils.StringUtils;
import com.liqi.common.utils.excel.ExcelUtils;
import com.liqi.common.utils.uuid.GenerateCodeUtils;
import com.liqi.device.domain.DvBrand;
import com.liqi.device.domain.DvModule;
import com.liqi.device.mapper.DvBrandMapper;
import com.liqi.device.mapper.DvModuleMapper;
import com.liqi.device.service.IDvBrandService;
import com.liqi.system.domain.vo.BrandVo;
import com.liqi.system.domain.vo.SysRegionVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 品牌Service业务层处理
 *
 * @author ruoyi
 * @date 2022-02-11
 */
@Service
public class DvBrandServiceImpl implements IDvBrandService
{

    private static final Logger logger = LoggerFactory.getLogger(DvBrandServiceImpl.class);

    @Autowired
    private DvBrandMapper dvBrandMapper;

    @Autowired
    private DvModuleMapper dvModuleMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询品牌
     *
     * @param id 品牌主键
     * @return 品牌
     */
    @Override
    public DvBrand selectDvBrandById(Long id)
    {
        return dvBrandMapper.selectDvBrandById(id);
    }

    @Override
    public DvBrand selectDvBrandByCode(String code) {
        return dvBrandMapper.selectDvBrandByCode(code);
    }

    @Override
    public DvBrand selectDvBrandByName(String name) {
        return dvBrandMapper.selectDvBrandByName(name);
    }

    /**
     * 查询品牌列表
     *
     * @param dvBrand 品牌
     * @return 品牌
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<DvBrand> selectDvBrandList(DvBrand dvBrand)
    {
        return dvBrandMapper.selectDvBrandList(dvBrand);
    }

    @Override
    public String importModule(List<DvBrand> dvBrands) {
        StringBuilder sb=new StringBuilder();

        for(DvBrand dvBrand:dvBrands){
            String name = dvBrand.getName();
            String code = dvBrand.getCode();



            boolean b = ExcelUtils.checkStringIsNull(code, name);
            if(b==false){
                sb.append("第" + dvBrand.getRowNum() + "行：有值未填");
                if (sb.length() > 0 && sb.charAt(sb.length() - 1) == ',') {
                    sb.deleteCharAt(sb.length() -1 );
                }
                sb.append(";<br/>");
            }else {
                DvBrand brand = dvBrandMapper.selectDvBrandByCode(code);

                if (brand == null) {
                    brand = new DvBrand();
                   brand.setCode(code);
                   brand.setName(name);
                    dvBrandMapper.insertDvBrand(brand);
                }
            }
        }

        return sb.toString();

    }

    /**
     * 新增品牌
     *
     * @param dvBrand 品牌
     * @return 结果
     */
    @Override
    public int insertDvBrand(DvBrand dvBrand)
    {
        dvBrand.setCreateTime(DateUtils.getNowDate());
        int num = dvBrandMapper.insertDvBrand(dvBrand);
        //增删改刷新缓存
        refreshAllBrandCache();
        return num;
    }

    /**
     * 修改品牌
     *
     * @param dvBrand 品牌
     * @return 结果
     */
    @Transactional
    @Override
    public int updateDvBrand(DvBrand dvBrand)
    {
        DvBrand oldBrand = dvBrandMapper.selectDvBrandById(dvBrand.getId());
        //取得旧的模块数据，然后更新表dv_module的品牌信息字段
        List<DvModule> oldModule = dvModuleMapper.selectDvModuleByBrandCode(oldBrand.getCode());

        dvBrand.setUpdateTime(DateUtils.getNowDate());
        int d = dvBrandMapper.updateDvBrand(dvBrand);

        if(oldModule != null && oldModule.size() > 0){
            oldModule.forEach(p->{
                p.setBrandCode(dvBrand.getCode());
                p.setBrandName(dvBrand.getName());
                dvModuleMapper.updateDvModule(p);
            });
        }
        //增删改刷新缓存
        refreshAllBrandCache();
        return d;
    }

    /**
     * 批量删除品牌
     *
     * @param ids 需要删除的品牌主键
     * @return 结果
     */
    @Override
    public int deleteDvBrandByIds(Long[] ids)
    {
        int num = dvBrandMapper.deleteDvBrandByIds(ids);
        //增删改刷新缓存
        refreshAllBrandCache();
        return  num;
    }

    /**
     * 删除品牌信息
     *
     * @param id 品牌主键
     * @return 结果
     */
    @Override
    public int deleteDvBrandById(Long id)
    {
        int num = dvBrandMapper.deleteDvBrandById(id);
        //增删改刷新缓存
        refreshAllBrandCache();
        return num;
    }

    /**
     * 	校验编码是否唯一
     *
     * @param brand 需校验的
     * @return
     */
	@Override
	public String checkCodeUnique(DvBrand brand) {
		Long configId = StringUtils.isNull(brand.getId()) ? -1L : brand.getId();
		DvBrand info = dvBrandMapper.checkCodeUnique(brand.getCode());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != configId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
	}

    /**
     * 返回所有级联菜单品牌
     * @return
     */
    @Override
    public List<BrandVo> selectAllBrandVo() {
        List<BrandVo> list = redisCache .getCacheObject(RedisConstants.SYS_BRAND_ALL_KEY);
        if(list == null || list.size() < 1){
            list = refreshAllBrandCache();
        }
        return list;
    }


    private List<BrandVo> refreshAllBrandCache() {
        logger.info("refreshAllBrandCache重新获取所有品牌数据更新缓存");
        BrandVo brandVo = new BrandVo();
        List<BrandVo> list = dvBrandMapper.selectAllBrandVo();
        redisCache.setCacheObject(RedisConstants.SYS_BRAND_ALL_KEY, list, 8, TimeUnit.HOURS);
        return list;
    }
}
